package watchmessgae

import (
	"errors"
	"fmt"
	"strconv"
	"strings"

	"github.com/sirupsen/logrus"
)

// [厂商*设备ID*内容长度*消息标识符]
type WatchMessage struct {
	Sign               string
	Manufacturer       string
	IMEI               string
	ContentLength      int64
	MessageID          string
	MessageContentList []string
}

func ParseMessage(message string) (*WatchMessage, error) {
	// 校验消息长度
	if len(message) < 32 {
		return &WatchMessage{}, errors.New("message is too short")
	}
	// 去除签名
	sign := message[0:32]
	logrus.Info("sign:", sign)
	message = message[32:]

	// 按照*进行切割
	parts := strings.Split(message, "*")
	if len(parts) < 4 {
		return &WatchMessage{}, errors.New("message is invalid: " + message)
	}

	// 解析内容长度
	contentLength, err := strconv.ParseInt(parts[2], 16, 32)
	if err != nil {
		return &WatchMessage{}, err
	}
	messageList := strings.Split(parts[3], ",")
	// 创建WatchMessage结构体
	watchMessage := WatchMessage{
		Sign:          sign,
		Manufacturer:  parts[0],
		IMEI:          parts[1],
		ContentLength: contentLength,
		MessageID:     messageList[0],
	}
	watchMessage.MessageContentList = messageList[1:]

	return &watchMessage, nil
}

// 消息回复
func ReplyMessage(message *WatchMessage) string {
	contentLength := len(message.MessageID)
	return fmt.Sprintf("%s*%s*%04X*%s", message.Manufacturer, message.IMEI, contentLength, message.MessageID)
}
